package com.crm.service.permission;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.crm.dao.permission.RoleDAO;
import com.crm.exception.ServiceException;
import com.crm.pojo.Role;

@Service
@Transactional(rollbackFor = Exception.class)
public class RoleService {

	@Autowired
	private RoleDAO roleDAO;

	public List<Role> queryAlls(){
		return roleDAO.queryAll();
	}
	
	public Role queryNameOne(String text){
		return roleDAO.queryOneName(text);
	}
	
	public String queryRoleOneName(Long id){
		return roleDAO.queryRoleName(id);
	}
	
	
	/**
	 * 分页查询总记录数
	 * 
	 * @return
	 */
	public Long queryRoleCount() {
		return roleDAO.queryRoleCount();
	}

	/**
	 * 分页查询角色
	 * 
	 * @param curpage
	 * @param pagesize
	 * @return
	 */
	public List<Role> queryRoleAllPage(int curpage, int pagesize) {
		PageRequest page = new PageRequest(curpage - 1, pagesize);
		return roleDAO.queryRoleAll(page);
	}

	/**
	 * 根据角色名称模糊查询角色
	 * 
	 * @param rname
	 * @return
	 */
	public List<Role> queryRolesName(String text,int curpage, int pagesize) {
		PageRequest page = new PageRequest(curpage - 1, pagesize);
		return roleDAO.quertRoleName("%" + text + "%",page);
	}

	/**
	 * 根据角色名称模糊查询角色总记录数
	 * 
	 * @return
	 */
	public Long queryRoleNameCount(String text) {
		return roleDAO.queryRoleNameCount("%" + text + "%");
	}
	/**
	 * 添加角色
	 * 
	 * @param rname
	 */
	public void addRole(String text) throws ServiceException {
		try {
				Role r = new Role();
				r.setRname(text);
				r.setRcreateTime(new Date());
				r.setRstatus("是");
				roleDAO.save(r);
		} catch (Exception e) {
			e.printStackTrace();
			throw new ServiceException(e);
		}
		
	}

	/**
	 * 删除角色
	 * 
	 * @param rId
	 */
	public void deleteRole(Long id) {
		Role role = roleDAO.findOne(id);
		role.setRstatus("否");
		roleDAO.save(role);
	}

	/**
	 * 根据角色ID查询角色
	 * 
	 * @param rId
	 * @return
	 */
	public Role queryRole(Long id) {
		return roleDAO.findOne(id);
	}

	/**
	 * 修改角色信息
	 * 
	 * @param rId
	 * @param rname
	 * @param rstatus
	 */
	public void updateRole(Long id, String text) throws ServiceException {
		try {
			Role role = roleDAO.findOne(id);
			role.setRname(text);
			roleDAO.save(role);
		} catch (Exception e) {
			e.printStackTrace();
			throw new ServiceException(e);
		}
	}

}
